// src/sub/commands.rs
use tauri_plugin_dialog::{DialogExt,MessageDialogKind,MessageDialogButtons};
use crate::sub::dbop;
use crate::entity::comm::{Page,User}; // 修改这里
#[tauri::command]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!  Good Day!!!! O(∩_∩)O~~", name)
}


#[tauri::command]
pub fn open_file(app:tauri::Window)->String  {
    let file_paths = app
    .dialog()
    .file()
    .blocking_pick_files();

    match file_paths {
        Some(paths) => {
            if paths.is_empty() {
                String::new() // 如果没有选择文件，返回空字符串
            } else {
                // 将所有选择的文件路径转换为字符串并用逗号分隔
                paths
                    .iter()
                    .map(|path| path.to_string())
                    .collect::<Vec<String>>()
                    .join(", ")
            }
        }
        None => String::new(), // 如果用户取消，返回空字符串
    }
}
// 打开确认弹出框并居中
#[tauri::command]
pub fn open_confirm(app:tauri::Window) -> bool {
    let dialog = app.dialog().message("Tauri is Awesome")
    .title("Tauri is Awesome")
    .buttons(MessageDialogButtons::YesNo)
    .kind(MessageDialogKind::Info);
    dialog.blocking_show()  
}

//调用sqltecmd 创建表
#[tauri::command]
pub fn create_table() -> Result<String, String> {
    match dbop::init_user_table() {
        Ok(_) => Ok("创建成功!".to_string()),
        Err(err) => Err(format!("创建表错误: {}", err)),
    }
}
#[tauri::command]
pub fn drop_table() -> Result<String, String> {
    match dbop::drop_table() {
        Ok(_) => Ok("删除表成功!".to_string()),
        Err(err) => Err(format!("删除表错误: {}", err)),
    }
}
//创建用户命令 使用User sstruct 接收 
#[tauri::command]
pub fn add_user(user: User) -> Result<String, String> {
    //打印用户信息
    dbop::add_user(user).map(|_| "User added successfully!".to_string())
        .map_err(|err| format!("Error adding user: {}", err))
}
//调用 query_user_page 分页查询用户信息
#[tauri::command]
pub fn query_user_page(page: i32, rows: i32,user: User) -> Result<Page<User>, String> {
    // 调用查询用户信息的函数，传入页码和每页大小
    dbop::query_user_page(page, rows,user).map_err(|err| format!("Error querying users: {}", err))  
}